<template>
    <a-modal :open="open" title="导入文件" :footer="null" width="720px" @cancel="handleCancel">
        <a-upload-dragger v-model:fileList="fileList" name="file" :multiple="false"
            action="/api/api-knowledge/knowledge/core/knowledgeBaseDetails/createByFile" @change="handleChange"
            :data="fileData" :headers="headers" :beforeUpload="beforeUpload" class="upload-file">
            <p class="ant-upload-drag-icon">
                <inbox-outlined></inbox-outlined>
            </p>
            <p class="ant-upload-text">拖拽文件至此，或者选择文件</p>
            <p class="ant-upload-hint">
                支持 TXT、 MARKDOWN、 MDX、 PDF、 HTML、 XLSX、 XLS、 DOCX、 CSV、 MD、 HTM，每个文件不超过 15MB
            </p>
        </a-upload-dragger>
        <div class="modal-footer">
            <a-button @click="handleCancel" class="close-btn">关闭</a-button>
        </div>
    </a-modal>
</template>
<script setup>
import { ref, defineProps, defineEmits, watch, reactive } from 'vue';
import { message } from 'ant-design-vue';
import { TokenUtil } from '@lowcode/jpaas-base-lib'
const props = defineProps({
    open: {
        type: Boolean,
        default: false
    },
    selectedKnowledge: {
        type: Object,
        default: {}
    },
    knowledgeId: {
        type: String,
        default: "",
    }
});
watch(() => props.open, (newValue) => {
    if (newValue) {
        fileList.value = [];
        fileData.value = {
            parentId: props.selectedKnowledge?.id || '',
            knowledgeId: props.knowledgeId
        };
        if (token) {
            headers['Authorization'] = 'Bearer ' + token;
            console.log(headers)
        }
    }
})
const fileData = ref({});
const headers = reactive({
    Authorization: ""
});
const emits = defineEmits(['cancel', 'initData']);
const token = TokenUtil.getToken();
const fileList = ref([]);

const MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB

const handleChange = (info) => {
    const { file } = info;
    const status = file.status;
    if (status !== 'uploading') {
        console.log(file, info.fileList);
    }
    if (status === 'done') {
        message.success(`${file.name} 文件上传成功.`);
        emits('initData')
    } else if (status === 'error') {
        message.error(`${file.name} 文件上传失败.`);
    }
};

const beforeUpload = (file) => {
    if (file.size > MAX_FILE_SIZE) {
        message.error(`${file.name} 文件大小超过15MB`);
        return Upload.LIST_IGNORE;  // 阻止上传
    }
    return true;
};

// 取消按钮点击事件处理函数
const handleCancel = () => {
    emits('cancel');
};


</script>
<style scoped>
.modal-footer {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>
